package com.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class TimeServerHandle implements Runnable {
    private Selector selector;
    private ServerSocketChannel serverChannel;
    private volatile boolean stop;

    public TimeServerHandle(int port) {
        try {
            //1.打开ServerSocketChannel,监听客户端的链接
            serverChannel = ServerSocketChannel.open();
            //2.设置非阻塞模式,绑定监听端口
            serverChannel.configureBlocking(false);
            serverChannel.socket().bind(new InetSocketAddress(port),1024);
            //3.创建多路复用器
            selector = Selector.open();
            //4.将ServerSocketChannel注册到多路复用器selector上，监听ACCEPT事件
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("the Time server is start in port :"+port);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void stop(){
        this.stop = true;
    }

    @Override
    public void run() {
        while (!stop){
            try {
                //5.多路复用器在线程run里面轮训就绪的key，休眠事件1s,selector每隔1s唤醒一次
                selector.select(1000);
                SelectionKey key;
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                while (it.hasNext()){
                    key = it.next();
                    it.remove();

                    try {
                        handleInput(key);
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                        if(key.channel() != null){
                            key.channel().close();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(selector != null){
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理新接入的客户端请求消息
     */
    private void handleInput(SelectionKey key) throws IOException {
//        key.attachment();
        if (key.isValid()){
            //处理新接入的消息，判断事件类型
            if(key.isAcceptable()){
                //
                ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
                //6.多路复用器监听到有新的客户端接入，处理新的接入请求
                SocketChannel sc = ssc.accept();
                //7.设置客户端连接参数，链路为非阻塞模式
                sc.configureBlocking(false);
                //8.将新接入的客户端连接注册到多路复用器上，监听读操作，读取客户端发送的网络消息
                sc.register(selector,SelectionKey.OP_READ);
            }
            if(key.isReadable()){
                //Read data
                SocketChannel sc = (SocketChannel)key.channel();
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                //9.异步读取客户端请求的消息到缓冲区
                int readBytes = sc.read(readBuffer);
                //大于0 读取到字节，对字节进行编解码
                if (readBytes > 0){
                    //将缓冲区当前的limit设置成position,posotion设置为0，用于后续的缓冲区读操作
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    //10.decode消息
                    String body = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("the time server recevice order:"+body);
                    String currentTime = "服务端返回的消息";
                    //11写Buffer到Socketchannel
                    doWrite(sc,currentTime);
                }else if (readBytes<0){
                    //对端链路关闭
                    key.cancel();
                    sc.close();
                }
            }
        }
    }

    /**
     * 应答消息发送给客户端
     */
    private void doWrite(SocketChannel channel,String response) throws IOException {
        if(response !=null && response.trim().length()>0){
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer);
        }
    }
}
